/**
 *  Copyright (c) Filipe Manana <fdmanana@gmail.com>
 *  All rights reserved.
 * 
 *  This file is part of jsdet.
 *
 *  jsdet is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published
 *  by the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  jsdet is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with jsdet.  If not, see <http://www.gnu.org/licenses/>.
 *
 */


package jsdet.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author Filipe Manana
 * 
 */
public class ExpandDirectory {

	public static Set<String> getFiles(String directoryName, Pattern fileExtensionPattern) throws IllegalArgumentException {

		Set<String> filesFound = new LinkedHashSet<String>();
		File dir = new File(directoryName);

		if ( !dir.isDirectory() ) {
			Matcher m = fileExtensionPattern.matcher(directoryName);
			if ( m.matches() ) {
				filesFound.add(directoryName);
			}
			else {
				throw new IllegalArgumentException("Given directory `" + directoryName + "' is a file with a non matching extension");
			}

			return filesFound;
		}

		if ( !directoryName.endsWith(File.separator) ) {
			directoryName += File.separator;
		}

		String[] files = dir.list();
		List<String> subdirsFiles = new ArrayList<String>();

		for ( int i = 0; i < files.length; i++ ) {
			String fullName = directoryName + files[i];

			File f = new File(fullName);

			if ( f.isDirectory() ) {
				Set<String> subdirFiles = getFiles(fullName, fileExtensionPattern);
				subdirsFiles.addAll(subdirFiles);
			}
			else {
				Matcher m = fileExtensionPattern.matcher(fullName);

				if ( m.matches() ) {
					filesFound.add(fullName);
				}
			}
		}

		filesFound.addAll(subdirsFiles);

		return filesFound;
	}

}
